package com.jjty.dataGenerator.data.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jjty.dataGenerator.bg.entity.SchoolInfo;
import com.jjty.dataGenerator.bg.entity.StudentInfo;
import com.jjty.dataGenerator.bg.mapper.SchoolMapper;
import com.jjty.dataGenerator.common.ApiResult;
import com.jjty.dataGenerator.common.PageParamReader;
import com.jjty.dataGenerator.data.entity.AttendanceRecord;
import com.jjty.dataGenerator.data.entity.ScCallRecord;
import com.jjty.dataGenerator.data.entity.TemperatureRecord;
import com.jjty.dataGenerator.data.entity.XykRecord;
import com.jjty.dataGenerator.data.entity.vo.DataTypeConfig;
import com.jjty.dataGenerator.data.entity.vo.GeneratedData;
import com.jjty.dataGenerator.data.mapper.DataTypeConfigMapper;
import com.jjty.dataGenerator.data.mapper.OperationLogMapper;
import com.jjty.dataGenerator.data.service.DataGeneratorService;
import com.jjty.dataGenerator.data.service.OperationLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/data/sc")
public class DataGeneratorController {

    private final DataGeneratorService dataGeneratorService;

    public DataGeneratorController(DataGeneratorService dataGeneratorService) {
        this.dataGeneratorService = dataGeneratorService;
    }
    @Autowired
    private DataTypeConfigMapper dataTypeConfigMapper;
    @Autowired
    private SchoolMapper schoolMapper;
    @Autowired
    private OperationLogService operationLogService;

//    @RequestMapping("/callRecords")
//    public ApiResult callRecordsData(@RequestParam(defaultValue = "10") Integer numRecords, String appId, String ecCode,String terminalLocation) {
//        dataGeneratorService.callRecordsData(numRecords,appId,ecCode,terminalLocation);
//        return ApiResult.doSuccess("随机数据生成并保存成功,共生成"+numRecords+"条记录");
//    }
//    @RequestMapping("/queryCallRecords")
//    public ApiResult queryCallRecords(HttpServletRequest request, ScCallRecord param, String keyword) {
//        Page page = PageParamReader.read(request);
//        page = dataGeneratorService.getCallRecordsPage(page,param,keyword);
//        return ApiResult.querySuccess(page);
//    }
//
//    @RequestMapping("/xykRecords")
//    public String xykRecordsData(@RequestParam(defaultValue = "10") Integer numRecords, String appId, String ecCode,String schoolName) {
//        dataGeneratorService.xykRecordsData(numRecords,appId,ecCode,schoolName);
//        return "随机数据生成并保存成功，共生成 " + numRecords + " 条记录";
//    }
//    @RequestMapping("/queryXykRecords")
//    public ApiResult queryXykRecords(HttpServletRequest request, XykRecord param, String keyword) {
//        Page page = PageParamReader.read(request);
//        page = dataGeneratorService.getXykRecordsPage(page,param,keyword);
//        return ApiResult.querySuccess(page);
//    }
//
//    @RequestMapping("/attendanceRecords")
//    public String attendanceRecordsData(@RequestParam(defaultValue = "10") Integer numRecords, String appId, String ecCode,String terminalLocation) {
//        dataGeneratorService.attendanceRecordsData(numRecords,appId,ecCode,terminalLocation);
//        return "随机数据生成并保存成功，共生成 " + numRecords + " 条记录";
//    }
//    @RequestMapping("/queryAttendanceRecords")
//    public ApiResult queryAttendanceRecords(HttpServletRequest request, AttendanceRecord param, String keyword) {
//        Page page = PageParamReader.read(request);
//        page = dataGeneratorService.getAttendanceRecordsPage(page,param,keyword);
//        return ApiResult.querySuccess(page);
//    }
//
//    @RequestMapping("/temperatureRecords")
//    public String temperatureRecordsData(@RequestParam(defaultValue = "10") Integer numRecords, String appId, String ecCode,String terminalLocation) {
//        dataGeneratorService.temperatureRecordsData(numRecords,appId,ecCode,terminalLocation);
//        return "随机数据生成并保存成功，共生成 " + numRecords + " 条记录";
//    }
//    @RequestMapping("/queryTemperatureRecords")
//    public ApiResult queryTemperatureRecords(HttpServletRequest request, TemperatureRecord param, String keyword) {
//        Page page = PageParamReader.read(request);
//        page = dataGeneratorService.getTemperatureRecordsPage(page,param,keyword);
//        return ApiResult.querySuccess(page);
//    }

    @RequestMapping("/addConfig")
    public ApiResult addConfig(@RequestBody List<DataTypeConfig> configList) {
        for (DataTypeConfig config : configList) {
            // 检查配置是否已经存在
            QueryWrapper<DataTypeConfig> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("data_type", config.getDataType())
                    .eq("field_name", config.getFieldName())
                    .eq("school_name", config.getSchoolName());
            DataTypeConfig existingConfig = dataTypeConfigMapper.selectOne(queryWrapper);
            if (existingConfig != null) {
                return ApiResult.doFailure("配置信息已存在");
                // 如果配置已经存在，跳过插入操作
            }
            // 配置不存在，执行插入操作
            dataTypeConfigMapper.insert(config);
        }
        return ApiResult.doSuccess("配置信息保存成功");
    }
    // 新增获取下拉框选项的方法
    @RequestMapping("/getOptions")
    public ApiResult getDropdownOptions() {
        // 这里假设你要从 school_info 表中获取需要的字段的选项
        QueryWrapper<SchoolInfo> queryWrapper = new QueryWrapper<>();
        // 假设 school_info 表中有 school_name, school_type 等字段，你可以根据实际情况修改
        queryWrapper.select("school_name", "type");
        List<SchoolInfo> schoolInfoList = schoolMapper.selectList(queryWrapper);

        List<String> schoolNameOptions = schoolInfoList.stream()
                .map(SchoolInfo::getSchoolName)
                .distinct()
                .collect(Collectors.toList());

        List<String> schoolTypeOptions = schoolInfoList.stream()
                .map(SchoolInfo::getType)
                .distinct()
                .collect(Collectors.toList());

        java.util.Map<String, List<String>> optionsMap = new java.util.HashMap<>();
        optionsMap.put("schoolName", schoolNameOptions);
        optionsMap.put("type", schoolTypeOptions);

        return ApiResult.doSuccess("获取下拉框选项成功", optionsMap);
    }
    // 根据学校类型动态加载学校信息的接口
    @RequestMapping("/getSchoolsByType")
    public ApiResult getSchoolsByType(@RequestParam("type") String type) {
        QueryWrapper<SchoolInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        List<SchoolInfo> schoolInfoList = schoolMapper.selectList(queryWrapper);
        return ApiResult.doSuccess("获取学校信息成功", schoolInfoList);
    }
    @RequestMapping("/deleteConfig")
    public ApiResult deleteConfig(Integer id) {
        int result = dataTypeConfigMapper.deleteById(id);
        if (result > 0) {
            return ApiResult.doSuccess("配置信息删除成功");
        } else {
            return ApiResult.doFailure("配置信息删除失败");
        }
    }

    @RequestMapping("/updateConfig")
    public ApiResult updateConfig(@RequestBody DataTypeConfig config) {
        int result = dataTypeConfigMapper.updateById(config);
        if (result > 0) {
            return ApiResult.doSuccess("配置信息修改成功");
        } else {
            return ApiResult.doFailure("配置信息修改失败");
        }
    }

    @RequestMapping("/queryConfig")
    public ApiResult queryConfig(HttpServletRequest request, DataTypeConfig param, String keyword) {
        Page page = PageParamReader.read(request);
        page = dataGeneratorService.queryConfigByPages(page,param,keyword);
        return ApiResult.querySuccess(page);
        }

    @RequestMapping("/generateData")
    public ApiResult generateData(@RequestParam String dataType, @RequestParam List<String> schoolNames, HttpServletRequest request) {
        String operationIp = request.getRemoteAddr();
        String operationType = "生成数据";
        String operationStatus;
        try {
            dataGeneratorService.generateData(dataType, schoolNames);
            operationStatus = "成功";
        } catch (Exception e) {
            operationStatus = "失败";
            e.printStackTrace();
        }
        operationLogService.saveLog(operationType, operationIp, operationStatus,dataType);
        return ApiResult.doSuccess("随机数据生成并保存成功");
    }

    @RequestMapping("/queryDataByPages")
    public ApiResult queryDataByPages(HttpServletRequest request, GeneratedData param, String keyword) {
        Page page = PageParamReader.read(request);
        page = dataGeneratorService.queryDataByPages(page,param,keyword);
        return ApiResult.querySuccess(page);
    }

}